#include "HUD.h"
#include "Constants.h"
#include "base\Engine.h"
#include "game\World.h"
#include "renderer\DebugRenderer.h"

// ---------------------------------------------------------------
//  HUD
// ---------------------------------------------------------------
void HUD::init() {	
	m_TextNode = new ds::PlainTextNode("HUDText","BigXScale");
	gEngine->getWorld().attachNode(m_TextNode,"HUD");
	m_TextNode->setText("PointsTxt",ds::Vec2(140,20),ds::Color(1.0f,0.5f,0.0f,1.0f),"Points");
	m_TextNode->setText("TimerTxt",ds::Vec2(700,20),ds::Color(1.0f,0.5f,0.0f,1.0f),"Timer");
	m_TextNode->setText("Points",ds::Vec2(125,60),ds::Color(0.0f,0.5f,1.0f,1.0f),"000000");
	m_TextNode->setText("Timer",ds::Vec2(700,60),ds::Color(0.0f,0.5f,1.0f,1.0f),"00:00");
		
	mouseSprite = add(ds::Vec2(0,0),ds::Rect(32,0,30,30));
	reset();
	m_Timing = false;
}

void HUD::update(float elapsed) {
	if ( m_Running ) {
		if ( m_Timing ) {
			m_Timer += elapsed;
			if ( m_Timer >= 1.0f ) {
				--m_Seconds;				
				m_Timer = 0.0f;
				m_TextNode->setText("Timer",ds::Vec2(730,60),ds::Color(0.0f,0.5f,1.0f,1.0f),"%02d",m_Seconds);
				if ( m_Seconds <= 0 ) {
					m_Running = false;
					FIRE_EMPTY_EVENT(EVN_GAME_OVER);				
				}
			}
		}
		else {
			m_Timer += elapsed;
			if ( m_Timer >= 1.0f ) {
				++m_Seconds;
				m_Timer = 0.0f;
				if ( m_Seconds == 60 ) {
					m_Seconds = 0;
					++m_Minutes;					
				}
				m_TextNode->setText("Timer",ds::Vec2(700,60),ds::Color(0.0f,0.5f,1.0f,1.0f),"%02d:%02d",m_Minutes,m_Seconds);
			}
		}
	}
	int mx = gEngine->getMousePosX() - 15;
	int my = gEngine->getMousePosY() - 15;
	//gEngine->getDebugRenderer()->addText(ds::Vec2(10,0),ds::Color(1.0f,1.0f,1.0f,1.0f),"Mouse %d %d",gEngine->getMousePosX(),gEngine->getMousePosY());
	setPosition(mouseSprite,ds::Vec2(mx,my));
}

void HUD::activate(bool timing) {
	m_TextNode->setActive(true);
	m_Timing = timing;
	if ( timing ) {
		m_TTL = 5;
		m_Seconds = 5;
		m_TextNode->setText("Timer",ds::Vec2(730,60),ds::Color(0.0f,0.5f,1.0f,1.0f),"%02d",m_Seconds);
	}
	else {
		m_TextNode->setText("Timer",ds::Vec2(700,60),ds::Color(0.0f,0.5f,1.0f,1.0f),"00:00");
		reset();
	}
}

void HUD::deactivate() {
	m_Running = false;
	m_TextNode->setActive(false);
}

void HUD::setScore(int value) {
	m_TextNode->setText("Points",ds::Vec2(125,60),ds::Color(0.0f,0.5f,1.0f,1.0f),"%06d",value);	
	if ( m_Timing ) {
		m_Seconds = m_TTL;
		m_Timer = 0.0f;
		m_TextNode->setText("Timer",ds::Vec2(730,60),ds::Color(0.0f,0.5f,1.0f,1.0f),"%02d",m_Seconds);
	}
	
}

void HUD::process(ds::EventBuffer& buffer) {	
	if ( buffer.containsID(EVN_RESET_GAME) ) {
		reset();
	}	
	else if ( buffer.containsID(EVN_LEVEL_READY) ) {
		m_Running = true;
	}	
}
